package com.powernode.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.AuthConstants;
import com.powernode.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description:
 * @author: mky
 * @date: 2024/7/5 11:37
 * @version: 1.0
 */
@Component
public class LogoutSuccessfulHandler implements LogoutSuccessHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //token从redis删除，返回响应信息
        // 设置响应信息
        response.setContentType(AuthConstants.CONTENT_TYPE);
        response.setCharacterEncoding(AuthConstants.UTF_8);
        // 从请求头中获取token
        String authorization = request.getHeader(AuthConstants.AUTHORIZATION);
        String token = authorization.replaceFirst(AuthConstants.TOKEN_PREFIX,"");
        redisTemplate.delete(token);
        Result<String> result = Result.success(null);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(result);
        PrintWriter writer = response.getWriter();
        writer.write(s);
        writer.flush();
        writer.close();
    }
}
